package com.dyh.quickdemo.demos.rxjava;

import io.reactivex.Observable;

import java.util.function.Supplier;

public class Observables {
        static <T> Observable<T> of(T value){
            if(value == null){
                throw new NullPointerException();
            }
            else{
                return Observable.just(value);
            }
        }

        static <T> Observable<T> ofNullable(T value){
            return value == null ? Observable.empty() : Observable.just(value);
        }

        static <T> T get(Observable<T> observable){
            //observable.blockingSingle()
            return observable.blockingSingle();
        }

        static <T> T orElse(Observable<T> observable, T other){
            return observable.defaultIfEmpty(other).blockingSingle();
        }

        static <T> boolean isPresent(Observable<T> observable){
            return !observable.isEmpty().blockingGet();
        }

        static <T> T orElseGet(Observable<T> observable, Supplier<T> other) {
            return isPresent(observable) ? get(observable) : other.get();
        }

        static <T, X extends Throwable> T orElseThrow(Observable<T> observable, Supplier<? extends X> other) throws X {
            if (isPresent(observable)) {
                return get(observable);
            } else {
                throw other.get();
            }
        }
    }